﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using MyCommon.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCommon
{
    public class App
    {
        public static bool IsBuild { get; set; }
        public static IServiceProvider RootService => IsBuild ? InternalApp.RootService : null;
        public static HttpContext Context = RootService?.GetService<IHttpContextAccessor>()?.HttpContext;
        public static IServiceProvider GetServiceProvider( Type serviceType ,bool mustBuild=false,bool throwException = true)
        {
            if (Context?.RequestServices != null)
            {
                return Context.RequestServices;
            }
            if(RootService!=null) return RootService;


            ServiceProvider serviceProvider = InternalApp.InternalService.BuildServiceProvider();
            return serviceProvider;

        }
        public static TService GetService<TService>(bool mustBuild=true) where TService : class=>App.GetService(typeof(TService),null,mustBuild)as TService;

        public static object GetService(Type serviceType, IServiceProvider serviceProvider = null, bool mustBuild = true) => (serviceProvider ?? GetServiceProvider(serviceType, mustBuild, false)) ?. GetService(serviceType);


    }
}
